package com.hmi.simulatedrive.fragment

import android.os.Bundle
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebViewClient
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.SPUtils
import com.hmi.simulatedrive.databinding.FragmentWebrtcBinding
import com.hmi.simulatedrive.utils.Constant
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

class WebRTCFragment: BaseFragment() {
    var webrtcBinding: FragmentWebrtcBinding? = null
    val webRTCUrl: String = "http://www.baidu.com"
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        webrtcBinding = FragmentWebrtcBinding.inflate(inflater)
        val webSettings = webrtcBinding!!.webviewWebrtc.settings
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webrtcBinding!!.webviewWebrtc.webViewClient = WebViewClient()
        webrtcBinding!!.webviewWebrtc.loadUrl(webRTCUrl)
        EventBus.getDefault().register(this)
        return webrtcBinding?.root
    }

    override fun onResume() {
        super.onResume()
    }

    @Subscribe
    fun onEventMainThread(msg: Message) {
        if (msg.what == Constant.EVENT_WHAT_UPDATE_WEBRTC) {
            // 如果当前显示的地址与设置地址不同，则重新加载地址
            if (!SPUtils.getInstance().getString(Constant.SETTING_WEBRTC_URL, webRTCUrl).equals(webrtcBinding!!.webviewWebrtc.url)) {
                webrtcBinding!!.webviewWebrtc.loadUrl(SPUtils.getInstance().getString(Constant.SETTING_WEBRTC_URL, webRTCUrl))
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}